<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">

    

    <title>
      前端通信类以及跨域的几种方法 | 江月夜 
    </title>

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    
      <meta name="author" content="江月夜">
    
    

    <meta name="description" content="什么是同源策略及限制同源策略，它是由Netscape提出的一个著名的安全策略，现在所有支持JavaScript 的浏览器都会使用这个策略。限制从一个源加载的文档或脚本如何与来自另一个源的资源进行交互。这是一个用于隔离潜在恶意文件的关键的安全机制。所谓同源是指，域名，协议，端口（http协议的默认端口是80）相同。例如一">
<meta name="keywords" content="前端">
<meta property="og:type" content="article">
<meta property="og:title" content="前端通信类以及跨域的几种方法 | 江月夜">
<meta property="og:url" content="http://yoursite.com/2018/09/26/ajax/index.html">
<meta property="og:site_name" content="江月夜">
<meta property="og:description" content="什么是同源策略及限制同源策略，它是由Netscape提出的一个著名的安全策略，现在所有支持JavaScript 的浏览器都会使用这个策略。限制从一个源加载的文档或脚本如何与来自另一个源的资源进行交互。这是一个用于隔离潜在恶意文件的关键的安全机制。所谓同源是指，域名，协议，端口（http协议的默认端口是80）相同。例如一个浏览器的两个tab页中分别打开来百度和谷歌的页面，当浏览器的百度tab页执行一">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-10-29T09:05:35.642Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="前端通信类以及跨域的几种方法 | 江月夜">
<meta name="twitter:description" content="什么是同源策略及限制同源策略，它是由Netscape提出的一个著名的安全策略，现在所有支持JavaScript 的浏览器都会使用这个策略。限制从一个源加载的文档或脚本如何与来自另一个源的资源进行交互。这是一个用于隔离潜在恶意文件的关键的安全机制。所谓同源是指，域名，协议，端口（http协议的默认端口是80）相同。例如一个浏览器的两个tab页中分别打开来百度和谷歌的页面，当浏览器的百度tab页执行一">
    
    
    
      <link rel="icon" type="image/x-icon" href="/favicon.png">
    
    <link rel="stylesheet" href="/css/uno.css">
    <link rel="stylesheet" href="/css/highlight.css">
    <link rel="stylesheet" href="/css/archive.css">
    <link rel="stylesheet" href="/css/china-social-icon.css">

</head>
<body>

    <span class="mobile btn-mobile-menu">
        <i class="icon icon-list btn-mobile-menu__icon"></i>
        <i class="icon icon-x-circle btn-mobile-close__icon hidden"></i>
    </span>

    

<header class="panel-cover panel-cover--collapsed">


  <div class="panel-main">

  
    <div class="panel-main__inner panel-inverted">
    <div class="panel-main__content">

        

        <h1 class="panel-cover__title panel-title"><a href="/" title="link to homepage">江月夜</a></h1>
        <hr class="panel-cover__divider" />

        
        <p class="panel-cover__description">
          腹有诗书气自华
        </p>
        <hr class="panel-cover__divider panel-cover__divider--secondary" />
        

        <div class="navigation-wrapper">

          <nav class="cover-navigation cover-navigation--primary">
            <ul class="navigation">

              
                
                <li class="navigation__item"><a href="/#blog" title="" class="blog-button">首页</a></li>
              
                
                <li class="navigation__item"><a href="/about" title="" class="">关于</a></li>
              
                
                <li class="navigation__item"><a href="/archive" title="" class="">归档</a></li>
              

            </ul>
          </nav>

          <!-- ----------------------------
To add a new social icon simply duplicate one of the list items from below
and change the class in the <i> tag to match the desired social network
and then add your link to the <a>. Here is a full list of social network
classes that you can use:

    icon-social-500px
    icon-social-behance
    icon-social-delicious
    icon-social-designer-news
    icon-social-deviant-art
    icon-social-digg
    icon-social-dribbble
    icon-social-facebook
    icon-social-flickr
    icon-social-forrst
    icon-social-foursquare
    icon-social-github
    icon-social-google-plus
    icon-social-hi5
    icon-social-instagram
    icon-social-lastfm
    icon-social-linkedin
    icon-social-medium
    icon-social-myspace
    icon-social-path
    icon-social-pinterest
    icon-social-rdio
    icon-social-reddit
    icon-social-skype
    icon-social-spotify
    icon-social-stack-overflow
    icon-social-steam
    icon-social-stumbleupon
    icon-social-treehouse
    icon-social-tumblr
    icon-social-twitter
    icon-social-vimeo
    icon-social-xbox
    icon-social-yelp
    icon-social-youtube
    icon-social-zerply
    icon-mail

-------------------------------->

<!-- add social info here -->



<nav class="cover-navigation navigation--social">
  <ul class="navigation">

    
      <!-- Github -->
      <li class="navigation__item">
        <a href="https://github.com/ajiu9" title="">
          <i class='icon icon-social-github'></i>
          <span class="label">GitHub</span>
        </a>
      </li>
    

    <!-- China social icon -->
    <!--
    
      <li class="navigation__item">
        <a href="" title="">
          <i class='icon cs-icon-douban'></i>
          <span class="label">Douban</span>
        </a>
      </li>

      <li class="navigation__item">
        <a href="" title="">
          <i class='icon cs-icon-weibo'></i>
          <span class="label">Weibo</span>
        </a>
      </li>

    -->



  </ul>
</nav>



        </div>

      </div>

    </div>

    <div class="panel-cover--overlay"></div>
  </div>
</header>

    <div class="content-wrapper">
        <div class="content-wrapper__inner entry">
            

<article class="post-container post-container--single">

  <header class="post-header">
    
    <h1 class="post-title">前端通信类以及跨域的几种方法</h1>

    

    <div class="post-meta">
      <time datetime="2018-09-26" class="post-meta__date date">2018-09-26</time> 

      <span class="post-meta__tags tags">

          
            <font class="categories">
            &#8226; 分类:
            <a class="categories-link" href="/categories/通信/">通信</a>
            </font>
          

          
             &#8226; 标签:
            <font class="tags">
              <a class="tags-link" href="/tags/前端/">前端</a>
            </font>
          

      </span>
    </div>
    
    

  </header>

  <section id="post-content" class="article-content post">
    <h4 id="什么是同源策略及限制"><a href="#什么是同源策略及限制" class="headerlink" title="什么是同源策略及限制"></a>什么是同源策略及限制</h4><p>同源策略，它是由Netscape提出的一个著名的安全策略，现在所有支持JavaScript 的浏览器都会使用这个策略。限制从一个源加载的文档或脚本如何与来自另一个源的资源进行交互。这是一个用于隔离潜在恶意文件的关键的安全机制。<br>所谓同源是指，域名，协议，端口（http协议的默认端口是80）相同。<br>例如一个浏览器的两个tab页中分别打开来百度和谷歌的页面，当浏览器的百度tab页执行一个脚本的时候会检查这个脚本是属于哪个页面的，即检查是否同源，只有和百度同源的脚本才会被执行。如果非同源，那么在请求数据时，浏览器会在控制台中报一个异常，提示拒绝访问。<br>限制：</p>
<ul>
<li>Cookie、LocalStorage和IndexDB无法获取。</li>
<li>无法获取和操作DOM。</li>
<li>不能发送Ajax请求。</li>
</ul>
<h4 id="前后端如何通信"><a href="#前后端如何通信" class="headerlink" title="前后端如何通信"></a>前后端如何通信</h4><ul>
<li>Ajax：同源下的通信方式。</li>
<li>WebSocket：不受同源策略的限制，支持跨域。</li>
<li>CORS： CORS是跨源资源分享（Cross-Origin Resource Sharing）的缩写。它是W3C标准，是跨源AJAX请求的根本解决方法。相比JSONP只能发GET请求，CORS允许任何类型的请求。</li>
</ul>
<h4 id="如何创建Ajax"><a href="#如何创建Ajax" class="headerlink" title="如何创建Ajax"></a>如何创建Ajax</h4><p>需要知道以下几点：</p>
<ul>
<li>XMLHttpRequest的工作原理</li>
<li>兼容性处理（XMLHttpRequest只在高版本的浏览器支持）</li>
<li>事件的触发条件</li>
<li>事件的触发顺序</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line">util.ajax = <span class="function"><span class="keyword">function</span>(<span class="params">options</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> opt = <span class="built_in">Object</span>.assin(&#123;</span><br><span class="line">    url: <span class="string">''</span>,</span><br><span class="line">    ype: <span class="string">'get'</span>,</span><br><span class="line">    data: &#123;&#125;,</span><br><span class="line">    success: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;&#125;,</span><br><span class="line">    error: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;&#125;,</span><br><span class="line">  &#125;, options);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (opt.url) &#123;</span><br><span class="line">    <span class="comment">// 兼容性处理</span></span><br><span class="line">    <span class="keyword">var</span> xhr = XMLHttpRequest</span><br><span class="line">        ? <span class="keyword">new</span> XMLHttpRequest()</span><br><span class="line">        : <span class="keyword">new</span> ActiveXObject(<span class="string">'Microsoft.XMLHTTP'</span>);</span><br><span class="line">    <span class="keyword">var</span> data = opt.data,</span><br><span class="line">        url = opt.url,</span><br><span class="line">        type = opt.type.toUpperCase(),</span><br><span class="line">        dataArr = [];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> k <span class="keyword">in</span> data) &#123;</span><br><span class="line">      dataArr.push(k + <span class="string">'='</span> + data[k]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (type === <span class="string">'GET'</span>) &#123;</span><br><span class="line">      url = url + <span class="string">'?'</span> + dataArr.join(<span class="string">'&amp;'</span>);</span><br><span class="line">      xhr.open(type, url.replace(<span class="regexp">/\?$/g</span>, <span class="string">''</span>), <span class="literal">true</span>);</span><br><span class="line">      xhr.send();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (type === <span class="string">'POST'</span>) &#123;</span><br><span class="line">      xhr.open(type, url, <span class="literal">true</span>);</span><br><span class="line">      xmlhttp.setRequestHeader(<span class="string">'Content-type'</span>, <span class="string">'application/x-www-form-urlencoded'</span>);</span><br><span class="line">      xhr.send(dataArr.join(<span class="string">'&amp;'</span>));</span><br><span class="line">    &#125;</span><br><span class="line">    xhr.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (xhr.status === <span class="number">200</span> || xhr === <span class="number">304</span>) &#123;</span><br><span class="line">        <span class="keyword">var</span> res;</span><br><span class="line">        <span class="keyword">if</span> (opt.success &amp;&amp; opt.success <span class="keyword">instanceof</span> <span class="built_in">Function</span>) &#123;</span><br><span class="line">          res = xhr.responseText;</span><br><span class="line">          <span class="keyword">if</span> (<span class="keyword">typeof</span> res ==== <span class="string">'string'</span>) &#123;</span><br><span class="line">            res = <span class="built_in">JSON</span>.parse(res);</span><br><span class="line">            opt.success.call(xhr, res);</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (opt.error &amp;&amp; opt.error <span class="keyword">instanceof</span> <span class="built_in">Function</span>) &#123;</span><br><span class="line">          opt.error.call(xhr, res);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="跨域通信的几种方式"><a href="#跨域通信的几种方式" class="headerlink" title="跨域通信的几种方式"></a>跨域通信的几种方式</h4><ul>
<li>jsonp</li>
<li>Hash</li>
<li>webSocket</li>
<li>postMessage</li>
<li>CORS</li>
</ul>
<p><strong>1.jsonp</strong><br>jsonp原理： 通过<code>&lt;script&gt;</code>标签的异步加载来实现。例如在<code>&lt;head&gt;</code>标签中通过<code>&lt;script&gt;</code>中的url加载的js。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * [function 拼接url]</span></span><br><span class="line"><span class="comment">   * @param  &#123;[Object]]&#125; data [description]</span></span><br><span class="line"><span class="comment">   * @return &#123;[value=key&amp;value1=key1]&#125;        [description]</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="keyword">var</span> util = &#123;&#125;</span><br><span class="line">  util.param = <span class="function"><span class="keyword">function</span> (<span class="params">data</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> url = <span class="string">''</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> k <span class="keyword">in</span> data) &#123;</span><br><span class="line">      <span class="keyword">let</span> value = data[k] !== <span class="literal">undefined</span> ? data[k] : <span class="string">''</span></span><br><span class="line">      url += <span class="string">`&amp;<span class="subst">$&#123;k&#125;</span>=<span class="subst">$&#123;<span class="built_in">encodeURIComponent</span>(value)&#125;</span>`</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> url ? url.substring(<span class="number">1</span>) : <span class="string">''</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">  * [function 判断是否为函数]</span></span><br><span class="line"><span class="comment">  * @param  &#123;[type]&#125; source [description]</span></span><br><span class="line"><span class="comment">  * @return &#123;[type]&#125;        [description]</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">  util.isFunction = <span class="function"><span class="keyword">function</span> (<span class="params">source</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">'[object Function]'</span> === <span class="built_in">Object</span>.prototype.toString.call(source);</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">  * [function 获取一个随机的5位字符串]</span></span><br><span class="line"><span class="comment">  * @param  &#123;[type]&#125; prefix [description]</span></span><br><span class="line"><span class="comment">  * @return &#123;[type]&#125;        [description]</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">  util.getName = <span class="function"><span class="keyword">function</span> (<span class="params">prefix</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> prefix + <span class="built_in">Math</span>.random().toString(<span class="number">36</span>).replace(<span class="regexp">/[^a-z]+/g</span>, <span class="string">''</span>).substr(<span class="number">0</span>, <span class="number">5</span>);</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">  * [function 在页面中注入js脚本]</span></span><br><span class="line"><span class="comment">  * @param  &#123;[type]&#125; url     [description]</span></span><br><span class="line"><span class="comment">  * @param  &#123;[type]&#125; charset [description]</span></span><br><span class="line"><span class="comment">  * @return &#123;[type]&#125;         [description]</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"> util.createScript = <span class="function"><span class="keyword">function</span> (<span class="params">url, charset</span>) </span>&#123;</span><br><span class="line">     <span class="keyword">var</span> script = <span class="built_in">document</span>.createElement(<span class="string">'script'</span>);</span><br><span class="line">     script.setAttribute(<span class="string">'type'</span>, <span class="string">'text/javascript'</span>);</span><br><span class="line">     charset &amp;&amp; script.setAttribute(<span class="string">'charset'</span>, charset);</span><br><span class="line">     script.setAttribute(<span class="string">'src'</span>, url);</span><br><span class="line">     script.async = <span class="literal">true</span>;</span><br><span class="line">     <span class="keyword">return</span> script;</span><br><span class="line"> &#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// jsop实现</span></span><br><span class="line">util.jsonp = <span class="function"><span class="keyword">function</span>(<span class="params">url, data, onsuccess, onerror, charset</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 第一步，全局注册一个callback回调函数</span></span><br><span class="line">  <span class="keyword">var</span> callbackName = util.getName(_callback);</span><br><span class="line">  <span class="built_in">window</span>[callbackName] = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (onsuccess &amp;&amp; onsuccess.util.isFunction) &#123;</span><br><span class="line">      onsuccess(<span class="built_in">arguments</span>[<span class="number">0</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 第二步 动态创建Script标签</span></span><br><span class="line">  url += (url.indexOf(<span class="string">'?'</span>) &lt; <span class="number">0</span> ? <span class="string">'?'</span> : <span class="string">'&amp;'</span>) + util.param(data);</span><br><span class="line">  <span class="keyword">var</span> script = util.createScript(url + <span class="string">'&amp;callback='</span> + callbackName, charset);</span><br><span class="line">  <span class="comment">// 第三步 发送script请求</span></span><br><span class="line">  <span class="built_in">document</span>.getElementsByTagName(<span class="string">'head'</span>)[<span class="number">0</span>].appendChild(script);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 第四步 监听函数</span></span><br><span class="line">  script.onload = script.onreadystatechange = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!script.readyState || <span class="regexp">/loaded|complete/</span>.test(script.readyState)) &#123;</span><br><span class="line">      script.onload = script.onreadystatechange = <span class="literal">null</span>;</span><br><span class="line">      <span class="comment">// 移除该script的 DOM 对象</span></span><br><span class="line">      <span class="keyword">if</span> (script.parentNode) &#123;</span><br><span class="line">          script.parentNode.removeChild(script);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 删除函数或变量</span></span><br><span class="line">      <span class="built_in">window</span>[callbackName] = <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">  script.onerror = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (onerror &amp;&amp; util.isFunction(onerror)) &#123;</span><br><span class="line">      onerror();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>实例：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">util.jsonp(<span class="string">'https://c.y.qq.com/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg'</span>,</span><br><span class="line">  &#123;</span><br><span class="line">    g_tk: <span class="number">5381</span>,</span><br><span class="line">    inCharset: <span class="string">'utf-8'</span>,</span><br><span class="line">    outCharset: <span class="string">'utf-8'</span>,</span><br><span class="line">    notice: <span class="number">0</span>,</span><br><span class="line">    format: <span class="string">'jsonp'</span>,</span><br><span class="line">    platform:<span class="string">' h5'</span>,</span><br><span class="line">    uin: <span class="number">0</span>,</span><br><span class="line">    needNewCode: <span class="number">1</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">arguments</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="comment">//返回qq音乐的接口数据</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * _callbackfczeb(&#123;"code":0,"data":&#123;"slider":[&#123;"linkUrl":"http://y.qq.com/m/act/sfhd/178.html?ADTAG=banner&amp;openinqqmusic=1","picUrl":"http://y.gtimg.cn/music/common/upload/MUSIC_FOCUS/353632.jpg","id":17883&#125;,&#123;"linkUrl":"http://y.qq.com/w/album.html?albummid=003eMz0J487bNo","picUrl":"http://y.gtimg.cn/music/common/upload/MUSIC_FOCUS/352853.jpg","id":17886&#125;,&#123;"linkUrl":"https://y.qq.com/m/digitalbum/gold/index.html?_video=true&amp;id=4677022&amp;g_f=shoujijiaodian","picUrl":"http://y.gtimg.cn/music/common/upload/MUSIC_FOCUS/352792.jpg","id":17876&#125;,&#123;"linkUrl":"http://y.qq.com/w/album.html?albummid=004b8jpC0eNsk2","picUrl":"http://y.gtimg.cn/music/common/upload/MUSIC_FOCUS/353070.jpg","id":17885&#125;,&#123;"linkUrl":"http://y.qq.com/w/album.html?albummid=001m2MBU3hVtdl","picUrl":"http://y.gtimg.cn/music/common/upload/MUSIC_FOCUS/353732.jpg","id":17890&#125;],"radioList":[&#123;"picUrl":"http://y.gtimg.cn/music/photo/radio/track_radio_199_13_1.jpg","Ftitle":"热歌","radioid":199&#125;,&#123;"picUrl":"http://y.gtimg.cn/music/photo/radio/track_radio_307_13_1.jpg","Ftitle":"一人一首招牌歌","radioid":307&#125;],"songList":[&#123;"songListDesc":"催泪大杀器！盘点演唱会经典万人大合唱","picUrl":"http://p.qpic.cn/music_cover/1Fr9IFMhWDPeUzWKVEjn3QTL2eX2QziaJmaL0ZAmsvtW71ic9IDUoYzg/300?n=1","id":"2646688496","accessnum":9598270,"songListAuthor":"金青松","pic_mid":"00333So02drvak","album_pic_mid":""&#125;,&#123;"songListDesc":"纳尼？这些华语歌手竟然会唱日语歌！","picUrl":"http://p.qpic.cn/music_cover/z8wAFqicQ1qhImeiajkrgiaR4hYM3pzsUULFnicXshFXdw9uGkm261Ex9g/300?n=1","id":"1144416825","accessnum":661314,"songListAuthor":"风吹草地","pic_mid":"0013j8zs1jRnLQ","album_pic_mid":""&#125;,&#123;"songListDesc":"精选内地十大民谣歌手代表作","picUrl":"http://p.qpic.cn/music_cover/hVUsfUFG2DV466URqw7PT7X66OknPIhic2mKDgicawN4qThIR7yhYY1w/300?n=1","id":"2043041547","accessnum":1172021,"songListAuthor":"１'s   ヽ","pic_mid":"004bFmjW2PXSqF","album_pic_mid":"0032YJyg2yF6Dd"&#125;,&#123;"songListDesc":"2016billboard嘻哈榜","picUrl":"http://p.qpic.cn/music_cover/tkduvk4dwqBxwzZhsNe0nwkwyiaLHVkxtla7REsX0yNkhibOH3Bdb2og/300?n=1","id":"2040362185","accessnum":1159152,"songListAuthor":"CREAMSAUCEONMEBABY","pic_mid":"000cL0xT2csmd7","album_pic_mid":"001iJq1y1Uq3zV"&#125;,&#123;"songListDesc":"浮光掠影：ACG纯音乐赏析合辑","picUrl":"http://p.qpic.cn/music_cover/XMPAjfs5uwGZdWII3osvAvCRyNWx8Pqy5Yice41OCZlBhLtk0p0icNvg/300?n=1","id":"1723063372","accessnum":965382,"songListAuthor":"黎桐同","pic_mid":"000xFtbN1l8ye8","album_pic_mid":"002egQPg3DWcCS"&#125;,&#123;"songListDesc":"trip-hop单曲大推荐","picUrl":"http://y.gtimg.cn/music/photo_new/T005R600x600M000002CJKAY1LKpcz.jpg?n=1","id":"3482605622","accessnum":357156,"songListAuthor":"哑忍","pic_mid":"","album_pic_mid":"004aOQhn3PPOpK"&#125;]&#125;&#125;)</span></span><br><span class="line"><span class="comment"> * /</span></span><br></pre></td></tr></table></figure></p>
<p><strong>2.Hash（片段识别符）</strong><br>url的<code>#</code>后面的内容就叫Hash。Hash的改变，页面不会刷新。这就是用 Hash 做跨域通信的基本原理(url的?后面的内容叫Search。Search的改变，会导致页面刷新)。<br>实例：<br>页面A通过iframe或frame嵌入了跨域页面B。<br>窗口可以把信息，写入子窗口的片段标识符。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> src = originURL + <span class="string">'#'</span> + data;</span><br><span class="line"><span class="built_in">document</span>.getElementById(<span class="string">'myIFrame'</span>).src = src;</span><br></pre></td></tr></table></figure></p>
<p>子窗口通过监听hashchange事件得到通知。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.onhashchange = checkMessage;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">checkMessage</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> message = <span class="built_in">window</span>.location.hash;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>同样的，子窗口也可以改变父窗口的片段标识符。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">parent.location.href= target + <span class="string">"#"</span> + hash;</span><br></pre></td></tr></table></figure>
<p><strong>3.postMessage</strong><br>HTML5引入了一个全新的API：跨文档通信 API（Cross-document messaging）。这个API为window对象新增了一个window.postMessage方法，允许跨窗口通信，不论这两个窗口是否同源。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// postMessage</span></span><br><span class="line"><span class="comment">// 窗口A(http:A.com)向跨域的窗口B(http:B.com)发送信息</span></span><br><span class="line">Bwindow.postMessage(<span class="string">'data'</span>, <span class="string">'http://B.com'</span>);</span><br><span class="line"><span class="comment">// 在窗口B中监听</span></span><br><span class="line">Awindow.addEventListener(<span class="string">'message'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">event</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(event.origin); <span class="comment">// 发送消息的窗口</span></span><br><span class="line">    <span class="built_in">console</span>.log(event.source); <span class="comment">// 消息发向的网址</span></span><br><span class="line">    <span class="built_in">console</span>.log(event.data); <span class="comment">// 消息内容</span></span><br><span class="line">&#125;, <span class="literal">false</span>);</span><br></pre></td></tr></table></figure>
<p><strong>4.webSocket</strong><br>WebSocket是一种通信协议，使用ws://（非加密）和wss://（加密）作为协议前缀。该协议不实行同源政策，只要服务器支持，就可以通过它进行跨源通信。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> ws = <span class="keyword">new</span> webSocket(<span class="string">"wss://echo.websocket.org"</span>);</span><br><span class="line">ws.onopen = <span class="function"><span class="keyword">function</span>(<span class="params">evt</span>) </span>&#123; </span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"Connection open ..."</span>); </span><br><span class="line">  ws.send(<span class="string">"Hello WebSockets!"</span>);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">ws.onmessage = <span class="function"><span class="keyword">function</span>(<span class="params">evt</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log( <span class="string">"Received Message: "</span> + evt.data);</span><br><span class="line">  ws.close();</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">ws.onclose = <span class="function"><span class="keyword">function</span>(<span class="params">evt</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"Connection closed."</span>);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>Websocket【参考资料】<a href="http://www.ruanyifeng.com/blog/2017/05/websocket.html" target="_blank" rel="noopener">http://www.ruanyifeng.com/blog/2017/05/websocket.html</a></p>
</blockquote>
<p>__4.CORS<br>CORS是一个W3C标准，全称是”跨域资源共享”（Cross-origin resource sharing）。它允许浏览器向跨源服务器，发出XMLHttpRequest请求，从而克服了AJAX只能同源使用的限制。<br>跨域时，浏览器会拦截Ajax请求，并在http头中加Origin。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// est</span></span><br><span class="line">fetch(<span class="string">'/some/url/'</span>, &#123;</span><br><span class="line">    method: <span class="string">'get'</span>,</span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span> (<span class="params">response</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 请求成功后执行操作</span></span><br><span class="line"></span><br><span class="line">&#125;).catch(<span class="function"><span class="keyword">function</span> (<span class="params">err</span>) </span>&#123;</span><br><span class="line"> <span class="comment">// 请求失败后执行操作</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>CORS【参考资料】<a href="http://www.ruanyifeng.com/blog/2016/04/cors.html" target="_blank" rel="noopener">http://www.ruanyifeng.com/blog/2016/04/cors.html</a></p>
</blockquote>

  </section>

  <section class="post-comments">

   <!--PC和WAP自适应版-->
<div id="SOHUCS" sid="请将此处替换为配置SourceID的语句" ></div> 
<script type="text/javascript"> 
(function(){ 
var appid = 'cytl2q04G'; 
var conf = 'prod_c6e77c75d2d767714e129c11e500044d'; 
var width = window.innerWidth || document.documentElement.clientWidth; 
if (width < 960) { 
window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){window.changyan.api.config({appid:appid,conf:conf})}); } })(); </script>
    
</section>


</article>


            <footer class="footer">

    <span class="footer__copyright">&copy; 2017 | 由<a href="https://hexo.io/">Hexo</a>| 主题<a href="https://github.com/someus/huno">Huno</a></span>
    
</footer>
        </div>
    </div>

    <!-- js files -->
    <script src="/js/jquery.min.js"></script>
    <script src="/js/main.js"></script>
    <script src="/js/scale.fix.js"></script>
    

    

    <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <script type="text/javascript"> 
        $(document).ready(function(){
            MathJax.Hub.Config({ 
                tex2jax: {inlineMath: [['[latex]','[/latex]'], ['\\(','\\)']]} 
            });
        });
    </script>


    

    <script src="/js/awesome-toc.min.js"></script>
    <script>
        $(document).ready(function(){
            $.awesome_toc({
                overlay: true,
                contentId: "post-content",
            });
        });
    </script>


    
    
    <!--kill ie6 -->
<!--[if IE 6]>
  <script src="//letskillie6.googlecode.com/svn/trunk/2/zh_CN.js"></script>
<![endif]-->

</body>
</html>
